/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-04-20 10:05:48
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
// 查询IP、经纬度、省市区
const search = (ip) => {
    var options = {
        uri: `http://ip-api.com/json/${ip}?lang=zh-CN`,
        json: true
    };

    const reqObj = request(options)
    return reqObj
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    getRawBody(req, async (err, body) => {
        //?ip=有值，怎么查值，无值自动抓取客户端ip
        var ip = req.queries.ip ? req.queries.ip : req.clientIP
        const data = await search(ip)
        if (data.status.includes('success')) {
            await sendResp(data)
        }
        else {
            await sendResp({
                data: "未查询到数据"
            })
        }
    });

    // 返回
    sendResp = (data) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: true,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }

}